package com.yupi.mianshizhiku.blackfilter;

import cn.hutool.bloomfilter.BitMapBloomFilter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import freemarker.template.utility.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 黑名单过滤工具类
 */
@Slf4j
public class BlackIpUtils {

    private static BitMapBloomFilter bloomFilter;

    //判断是否在黑名单中
    public static boolean isInBlack(String ip) {
        return bloomFilter.contains(ip);
    }

    /**
     * 重建黑名单
     * @param configInfo
     */
    public static void rebuildBlackIp(String configInfo) {
        if (StrUtil.isBlank(configInfo)){
            configInfo = "{}";
            log.error("黑名单配置为空，请检查配置");
        }
        Yaml yaml = new Yaml();
        Map map = yaml.loadAs(configInfo, Map.class);
        // 获取黑名单列表
        List<String> blackIpList = (List<String>) map.get("blackIpList");
        // 加锁，避免多线程同时重建
        synchronized (BlackIpUtils.class){
            if (CollUtil.isNotEmpty(blackIpList)){
                // 初始化布隆过滤器，注意构造参数的设置，可以根据ip数量和误判率进行调整
                BitMapBloomFilter bitMapBloomFilter = new BitMapBloomFilter(958506);
                for (String ip : blackIpList) {
                    bitMapBloomFilter.add(ip);
                }
                bloomFilter = bitMapBloomFilter;
                log.info("黑名单重建成功，共计{}个ip", blackIpList.size());
            }else {
                log.error("黑名单配置为空，请检查配置");
                bloomFilter = new BitMapBloomFilter(100);
            }
        }
    }
}
